package com.yuan.blog.job;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yuan.blog.constatns.RedisKey;
import com.yuan.blog.dto.EmailDto;
import com.yuan.blog.entity.EmailErrorEntity;
import com.yuan.blog.service.IEmailErrorService;
import com.yuan.blog.utils.MailUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class SendErrorEmailJob {

    @Autowired
    private IEmailErrorService emailErrorService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Scheduled(cron = "0/10 * * * * *")
    public void reSendEmail() {
        log.debug("定时任务开始发送邮件");
        Set<String> members = redisTemplate.opsForSet().members(RedisKey.EMAIL_ID_KEY);
        if(members.isEmpty()){
            return;
        }

        // 1.获取发送失败的邮件
        List<EmailErrorEntity> errorEmails = getErrorEmails();
        // 2.遍历重新发送邮件
        for (EmailErrorEntity errorEmail : errorEmails) {
            String emailText = errorEmail.getEmailText();
            try {
                int status = MailUtil.sendSimpleMail(JSON.parseObject(emailText, EmailDto.class));
                if (status > 0) {
                    // 重新发送成功，修改MySQL中邮件的状态
                    errorEmail.setStatus(2);
                    emailErrorService.updateById(errorEmail);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }


    }

    //获取错误邮件信息
    private List<EmailErrorEntity> getErrorEmails() {
        String json = redisTemplate.opsForValue().get(RedisKey.EMAIL_ERROR_KEY);
        if (!ObjectUtils.isEmpty(json)){
            JSONArray jsonArray = JSONArray.parseArray(json);
            List<EmailErrorEntity> emailErrorEntityList = JSONObject.parseArray(jsonArray.toJSONString(), EmailErrorEntity.class);
            return emailErrorEntityList;
        }

        QueryWrapper<EmailErrorEntity> wrapper = new QueryWrapper();
        wrapper.eq("status", 1);
        List<EmailErrorEntity> errorEntities = emailErrorService.list(wrapper);
        //使用fastjson将list转为string
        JSONArray jsonArray = JSON.parseArray(JSON.toJSONString(errorEntities));
        String errorEmails = jsonArray.toJSONString();
        redisTemplate.opsForValue().set(RedisKey.EMAIL_ERROR_KEY,errorEmails,60, TimeUnit.SECONDS);

        return errorEntities;
    }
}
